<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="14">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addCommodity">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格(元)" prop="goods_price"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight"></el-table-column>
        <el-table-column label="创建时间" prop="upd_time">
          <template slot-scope="scope">{{scope.row.upd_time | dateFormat}}</template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="butModify(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeDele(scope.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogModify"
      width="50%"
      @close="modifyClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form :model="userModify" :rules="rules" ref="userModify" label-width="70px" status-icon>
        <el-form-item label="用户名">
          <el-input v-model="userModify.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userModify.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userModify.email"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModify = false">取 消</el-button>
        <el-button type="primary" @click="butdialog('userModify')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 搜索字段传给后端获取数据
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 10
      },
      // 商品列表数据
      userlist: [],
      // 显示一共有多少条数据
      total: 0,
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      dialogModify: false,
      // 修改对话框用户信息数据
      userModify: {
        username: "",
        mobile: "",
        email: ""
      },
      // 表单验证
      rules: {
        username: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        email: [{ required: true, message: "请输入商品名称", trigger: "blur" }]
      }
    };
  },
  methods: {
    //获取商品列表数据接口
    async getUserList() {
      const result = await this.$http.get("goods", {
        params: this.queryInfo
      });
      console.log(result);
      this.userlist = result.data.goods;
      this.total = result.data.total;
    },
    // 监听 pagesize 改变的事件  一页显示多少条数据
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 监听添加用户对话框关闭事件
    dialogClose() {
      // 当对话框关闭时会触发表单重置事件
      this.$refs.ruleForm.resetFields();
    },
    modifyClose() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.userModify.resetFields();
    },
    // 点击确定按钮进行添加新用户
    addUser(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.post("users", this.ruleForm);
          if (result.meta.status == 201) {
            this.$message.success("用户创建成功！");
            this.dialogVisible = !this.dialogVisible; //创建成功对话框隐藏
            this.getUserList(); //重新加载列表数据
          }
        } else {
          this.$message.error("用户创建失败！");
        }
      });
    },
    // 点击修改按钮获取当前用户信息接口
    async butModify(id) {
      const result = await this.$http.get("users/" + id);
      if (result.meta.status == 200) {
        console.log("获取成功");
        this.userModify = result.data;
        console.log(this.userModify);
      } else {
        this.$message.error("用户信息获取失败！");
      }
      this.dialogModify = !this.dialogModify;
    },
    // 修改用户修改信息并提交接口
    butdialog(userModify) {
      this.$refs[userModify].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.put(
            "users/" + this.userModify.id,
            this.userModify
          );
          if (result.meta.status == 200) {
            this.$message.success("用户信息修改成功！");
            this.dialogModify = !this.dialogModify; //创建成功对话框隐藏
            this.getUserList(); //重新加载列表数据
          }
        } else {
          this.$message.error("用户创建失败！");
        }
      });
    },
    // 根据ID删除对应的用户信息
    async removeDele(id) {
      // 弹框询问用户是否删除数据
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false
        }
      ).catch(err => err);
      console.log(res);
      console.log(id);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete("goods/" + id);
        if (reslut.meta.status == 200) {
          this.getUserList();
          this.$message.success("您已删除该商品！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    },
    // 添加商品点击事件
    addCommodity() {
      this.$router.push({ path: "/goods/add" });
    }
  },
  created() {
    this.getUserList();
  }
};
</script>

<style lang="stylus" scoped></style>
